local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
local pcall = pcall
local unpack = unpack
local math = math
local conf = require "conf"
local util = require "util"
local pairs = pairs
local uploader = require "uploader"
package.cpath = "/opt/xyitech/jieyan-backend-production/xbit/?.so"
local xbit = require 'xbit'
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)
_VERSION = '0.1'
 _int32_t = 0
 _int16_t = 1
 _float = 2
 _uint32_t = 4
 _uint16_t = 5
 _uint8_t = 6
 _int8_t = 7
 _dynamic = 99
 local _fs = util.getChannel("fs_all")
 local _ws = util.getChannel("ws_all")

function create(user, args)
    local path = ""

    local db = conf.get_mysql()
    local vals = {}
    if args.id and tonumber(args.id) then
        vals[#vals + 1] = "id = " .. tonumber(args.id)
    end

    if args.belong_id then
        vals[#vals + 1] = "belong_id = " .. args.belong_id
    end

    if args.type then
        vals[#vals + 1] = "type = " .. ngx.quote_sql_str(args.type)
    end

    if args.path then
        vals[#vals + 1] = "path = " .. ngx.quote_sql_str(path .. args.path)
    else
        path = path .. args.belong_id .. "_" .. os.time() .. ".jpg"
        vals[#vals + 1] = "path = " .. ngx.quote_sql_str(path)
    end

    if args.data then
        uploader.base64(args.data, path)
    end

    vals[#vals + 1] = "create_time = " .. os.time()
    vals[#vals + 1] = "update_time = " .. os.time()
    local sql = "INSERT INTO `image` SET " .. table.concat(vals, ",")
    ngx.log(ngx.ERR, sql)
    local res = db:query(sql)
    return res
end

function createController(user, args)
    local res = create(user, args)
    local db = conf.get_mysql()

    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '创建失败'
        }))
        ngx.exit(200)
    else
        local insert_id = res.insert_id
        if insert_id < 1 then
            res = db:query("SELECT LAST_INSERT_ID() AS insert_id")
            if res and res[1] and res[1].insert_id then
                insert_id = res[1].insert_id
            end
        end
        ngx.print(json.encode({
            err = 0,
            id = insert_id,
            msg = '创建成功'
        }))
        ngx.exit(200)
    end
end

function search(user, args)
    local db = conf.get_mysql()
    local sql = nil
    local count = nil
    local res = nil
    
    sql = "SELECT * FROM `image` WHERE 1=1"

    if args.type then
        sql = sql ..  " AND `image`.type = " .. args.type
    end

    if args.id then
        sql = sql ..  " AND `image`.id = " .. args.id
    end

    local count = #(db:query(sql) or {})
    if page_no and page_size then
        sql = sql .. " LIMIT " .. (page_no * page_size) .. "," .. page_size
    end
    
    ngx.log(ngx.ERR, sql)
    res = db:query(sql)
    return res, count
end

function searchController(user, args)
    local res, count = search(user, args)
    if not res then
        ngx.print(json.encode({
            err = 1,
            msg = {}
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res,
            count = count
        }))
        ngx.exit(200)
    end
end

function update(user, args)
    local db = conf.get_mysql()
    local vals = {}
    if args.id and tonumber(args.id) then
        vals[#vals + 1] = "id = " .. tonumber(args.id)
    end

    if args.belong_id then
        vals[#vals + 1] = "belong_id = '" .. args.belong_id .. "'"
    end

    if args.type then
        vals[#vals + 1] = "type = " .. args.type
    end

    if args.path then
        vals[#vals + 1] = "path = " .. args.path
    end

    vals[#vals + 1] = "update_time = " .. os.time()

    local sql = "UPDATE `image` SET " .. table.concat(vals, ",") .. " WHERE id = " .. id
    ngx.log(ngx.ERR, sql)
    local res = db:query(sql)--AND aid = " .. aid
    return res
end

function updateController(user, args)
    local res = update(user, args)
    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '更新失败'
        }))
        ngx.exit(200)
    else 
        ngx.print(json.encode({
            err = 0,
            msg = '更新成功'
        }))
        ngx.exit(200)
    end
end

function delete(user, args)
    local db = conf.get_mysql()

    local res = db:query("DELETE FROM `image` WHERE id = " .. args.id)
    return res
end

function deleteController(user, args)
    if not args.id then
        ngx.print(json.encode({
            err = 2,
            msg = '缺少id'
        }))
    end
    local res = delete(user, args)
    if not res or res.affected_rows < 1 then
        ngx.print(json.encode({
            err = 1,
            msg = '更新失败'
        }))
        ngx.exit(200)
    else 
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end


function default(args)    
    if args.action == 'search' then
        local user = conf.parse_token(args, "plane")
        searchController(user, args)
    elseif args.action == 'create' then
        local user = conf.parse_token(args, "plane")
        createController(user, args)
    elseif args.action == 'update' then
        local user = conf.parse_token(args, "plane")
        updateController(user, args)
    elseif args.action == 'delete' then
        local user = conf.parse_token(args, "plane")
        deleteController(user, args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
